import fs from 'fs-extra'
import semver from 'semver'
import inquirer from 'inquirer'
import {
  PRE_RELEASE,
  PRE_RELEASE_TYPES,
  RELEASE_TYPES,
  packages,
  proPkg
} from './config'
import {
  buildPackage,
  publish,
  pushGithub,
  updateLockfile,
  updateVersion
} from './utils'
async function main() {
  const pkgJson = await fs.readJSON(proPkg)
  const currentVersion = pkgJson.version

  const releaseChoices: any[] = RELEASE_TYPES.map((type: any) => {
    const sv = semver.inc(currentVersion, type)
    return {
      name: `${type} (${sv})`,
      value: sv
    }
  })
  let targetVersion = currentVersion
  const { release } = await inquirer.prompt([
    {
      type: 'list',
      name: 'release',
      choices: releaseChoices.concat(PRE_RELEASE),
      message: 'Select release type'
    }
  ])
  targetVersion = release
  if (release === PRE_RELEASE) {
    const prereleaseChoices = PRE_RELEASE_TYPES.map((type) =>
      semver.inc(pkgJson.version, PRE_RELEASE, type)
    )
    const { prerelease } = await inquirer.prompt([
      {
        type: 'list',
        name: 'prerelease',
        choices: prereleaseChoices,
        message: 'Select prerelease version'
      }
    ])
    targetVersion = prerelease
  }
  // 更新版本
  updateVersion(targetVersion)
  // 更新npm-lock
  await updateLockfile()
  // 打包
  await buildPackage()
  // 推送远程仓库
  await pushGithub(targetVersion)
  // 推送到npm
  packages.forEach((pkg) => {
    publish(pkg)
  })
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})
